use winreg::transaction::Transaction;
use winreg::RegKey;
use winreg::enums::HKEY_CURRENT_USER;
use crate::prompt_theme::MyTheme;
use dialoguer::Select;
use crate::utils::MyData;
use regex::Regex;
use std::{fs, env};
use std::fs::File;
use std::io::{BufReader, BufRead};

pub struct Activate{}
/// 激活相关操作
///删除HKEY_CURRENT_USER\SOFTWARE\PremiumSoft\Data。
//
//展开HKEY_CURRENT_USER\SOFTWARE\Classes\CLSID，然后展开每一个子文件夹查看，如果里面只包含一个名为Info的文件夹，删掉它即可。
impl  Activate {

    /// run
    pub fn run(&self,soft:&str) {
        match soft {
            ""   => {
                let selections = &[
                    "Navicat",
                    "JetBrains IDE"
                ];

                let selection = Select::with_theme(&MyTheme::custom())
                    .with_prompt("请选择软件:")
                    .items(&selections[..])
                    .interact_opt()
                    .unwrap();
                if let Some(selection) = selection {
                    // println!("selection is {}",selection);
                    // println!("选项：{}",selections[selection]);
                    match selection {
                        0 => self.navicat(),
                        1 => self.jetbrains(),
                        _ => println!("没有匹配到 {} 或暂时不支持",selections[selection])
                    }
                }else {
                    println!("你没有选择任何选项")
                }
            },
            "navicat" =>  self.navicat(),
            "n" =>  self.navicat(),
            "jetbrains" =>  self.jetbrains(),
            "j" =>  self.jetbrains(),
            _ => println!("没有匹配到 {} 或暂时不支持",soft)
        }
    }


    /// 无限试用navicat
    pub fn navicat(&self){
        println!("activate navicat start");
        // 创建事务
        let t = Transaction::new().unwrap();
        let hkcu = RegKey::predef(HKEY_CURRENT_USER);
        // 打开
        let  result = hkcu.create_subkey_transacted("Software\\PremiumSoft",&t);
        match result {
            Ok((key,_disp)) => {
                // 删除navacate 14 Data
               if key.open_subkey("Data").is_ok() {
                   key.delete_subkey_all("Data").unwrap_or_else(|e|{
                       println!("delete_subkey_all Data error:{}",e)
                   });
               }
                // 删除navacate 15 Registration15XCS
                if key.open_subkey("NavicatPremium\\Registration15XCS").is_ok() {
                    key.delete_subkey_all("NavicatPremium\\Registration15XCS").unwrap_or_else(|e|{
                        println!("delete_subkey_all NavicatPremium\\Registration15XCS error:{}",e)
                    });
                }

            },
            Err(e) => println!("create_subkey_transacted Software\\PremiumSoft err {}",e)
        }


        // 打开
        let (key,_disp) = hkcu.create_subkey_transacted("SOFTWARE\\Classes\\CLSID",&t).unwrap();

        for _i in 1..5
        {
            // 一次删除不干净
            for item in key.enum_keys().map(|x| x.unwrap())
                {
                    let keyname = item.clone()+ "\\Info";
                    let rusult = key.open_subkey(&keyname);
                    match rusult {
                        Ok(_t) =>{
                            println!("{} have Info",&keyname);
                            println!("item: {}",&item);
                            key.delete_subkey_all(&item).unwrap_or_else(|e| {
                                println!("{}删除失败,err :{}",&item,e);
                            })
                        },
                        Err(_e) => {
                            continue;
                        }
                    };
                }
        }


        // 提交事务
        t.commit().unwrap();

        println!("activate navicat end");
    }

    pub fn jetbrains(&self) {


        let mut sources = MyData::new();
        sources.add("All",".?(IntelliJIdea|GoLand|CLion|PyCharm|DataGrip|RubyMine|AppCode|PhpStorm|WebStorm|Rider).*");
        sources.add("PhpStorm","PhpStorm");
        sources.add("GoLand","GoLand");
        sources.add("CLion","CLion");
        sources.add("PyCharm","PyCharm");
        sources.add("IntelliJIdea","IntelliJIdea");
        sources.add("WebStorm","WebStorm");
        sources.add("DataGrip","DataGrip");
        sources.add("RubyMine","RubyMine");
        sources.add("AppCode","AppCode");
        sources.add("Rider","Rider");


        let selection = Select::with_theme(&MyTheme::custom())
            .with_prompt("请选择:")
            .default(0)
            .items(&sources.names)
            .interact()
            .unwrap();

        let userprofile = env::var("USERPROFILE").unwrap();
        let appdata = env::var("APPDATA").unwrap()+"\\JetBrains";

        let re = Regex::new(sources.values[selection]).unwrap();

        // 删除 eval/*.key  other.xml
        self.delete_jetbrains_key(userprofile,&re,"config");
        self.delete_jetbrains_key(appdata,&re,"");

        // 删除注册表：HKEY_CURRENT_USER\Software\JavaSoft\Prefs\jetbrains\*

        // 创建事务
        let t = Transaction::new().unwrap();
        let hkcu = RegKey::predef(HKEY_CURRENT_USER);
        let (key,_disp) = hkcu.create_subkey_transacted("Software\\JavaSoft\\Prefs\\jetbrains",&t).unwrap();

        if selection == 0 {
            for item in sources.values {
                let _= key.delete_subkey_all(item);
            }
        }else {
            let _=key.delete_subkey_all(sources.values[selection]);
        }

        // 提交事务
        t.commit().unwrap();
        println!("配置完成");

    }

    fn delete_jetbrains_key(&self,jetbrains_path :String,re:&Regex,sub_path: &str) {
        fs::read_dir(jetbrains_path).unwrap()
            .map(|res| {
                let mut a = res.unwrap().path();
                if re.is_match(a.to_str().unwrap()) {
                    // 删除 eval
                    a.push(sub_path);
                    let mut b = a.clone();
                    a.push("eval");
                    if a.exists() {
                        // 删除该文件夹
                        fs::remove_dir_all(&a).unwrap();
                        println!("delete path :{} success",a.display());
                    }

                    // 删除 other.xml
                    b.push("options/other.xml");
                    // if fs::remove_file(&b).is_ok() {
                    //     println!("delete path {}",b.display());
                    // }
                    // 删除 other.xml 中的某一项 最好
                    if b.exists() {
                        let file = File::open(&b).unwrap();
                        let reader = BufReader::new(file);
                        let mut temp = String::new();

                        for (index,line) in reader.lines().enumerate() {
                            let t = line.unwrap();
                            if t.contains("evlsprt") {
                                continue;
                            }
                            if index !=0 {
                                temp += "\r\n";
                            }
                            temp += &t;
                        }
                        // 写入
                        let _= fs::write(b,temp);
                    }

                }
            })
            //.collect::<Vec<_>>();
            .for_each(drop)
    }


}


